package com.hethongviet.job.helpers;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.util.Log;

public class OpenHttpConnection
{
	public InputStream get(String urlString) throws IOException
	{
		InputStream in = null;
		int response = -1;

		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();

		if (!(conn instanceof HttpURLConnection)) throw new IOException(
				"Not an HTTP connection");
		try
		{
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK)
			{
				in = httpConn.getInputStream();
			}
		} catch (Exception ex)
		{
			throw new IOException("Error connecting");
		}
		return in;
	}

	public InputStream post(String baseUrlString, String dataString)
			throws IOException
	{
		InputStream in = null;
		URL url = new URL(baseUrlString);
		try
		{
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			Log.d("Debug", "1111");
			httpURLConnection.setDoOutput(true);
			Log.d("Debug", "11112");
			httpURLConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			Log.d("Debug", "11113");
			httpURLConnection.setRequestMethod("POST");
			Log.d("Debug", "11114");
			
			/* Error: timeout will stuck ?*/
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
					httpURLConnection.getOutputStream());
			/* end error */
			
			Log.d("Debug", "11115");
			outputStreamWriter.write(dataString);
			Log.d("Debug", "11116");
			outputStreamWriter.flush();
			Log.d("Debug", "11117");
			outputStreamWriter.close();
			Log.d("Debug", "11118");
			if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
			{
				in = httpURLConnection.getInputStream();
			}
			Log.d("Debug", "11119");

		} catch (Exception ex)
		{
			throw new IOException("Error connecting");
		}
		return in;
	}

	@SuppressWarnings("unused")
	private String replaceSpecialCharacters(String url)
	{
		String tempString = null;
		url = url.trim();
		if (url != null)
		{
			for (int i = 0; i < url.length(); i++)
			{
				char charAtI = url.charAt(i);
				if (charAtI == ' ') tempString += "%20";
				else if (charAtI == '@') tempString += "%40";
				else tempString += charAtI;
			}
		}
		return tempString;
	}
}
